<template>
  <div>
    <el-table
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
    >
      <el-table-column
        :label="$t('#')"
        prop="index"
        align="center"
        width="50"
      />
      <el-table-column label="事件处理">
        <template slot-scope="scope">
          <template v-for="(item, index) in eventSchema">
            <el-button :key="index" round size="mini" icon="el-icon-edit" @click="sourceOpen(item,scope.row)">{{ item }}</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      v-if="showWidgetEventDialogFlag"
      title="组件事件处理"
      :visible.sync="showWidgetEventDialogFlag"
      :show-close="true"
      append-to-body
      class="small-padding-dialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
    >
      <el-alert type="info" :closable="false" :title="eventName" />
      <code-editor ref="ecEditor" v-model="eventHandlerCode" :mode="'javascript'" :readonly="false" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="showWidgetEventDialogFlag = false">
          取消</el-button>
        <el-button type="primary" @click="saveEventHandler">
          确认</el-button>
      </div>
    </el-dialog>
    <el-drawer
      v-if="showDataSourceDialogFlagForm"
      v-loading="drawerLoading"
      direction="rtl"
      :modal="true"
      :size="820"
      :show-close="false"
      :visible.sync="showDataSourceDialogFlagForm"
      :destroy-on-close="true"
      :append-to-body="true"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :wrapper-closable="false"
      custom-class="ds-setting-drawer header-small-mb"
    >
      <template #title>
        <div>事件处理</div>
        <div style="float: right">
          <el-radio-group v-model="openDataSource" size="mini" style="margin-right:10px">
            <el-radio-button label="javascript" />
            <el-radio-button label="数据源" />
          </el-radio-group>
          <el-button type="primary" size="mini" @click="saveDataSource">
            保存</el-button>
          <el-button size="mini" @click="showDataSourceDialogFlagForm = false">
            取消</el-button>
        </div>
      </template>
      <template #default>
        <dataSourceForm ref="dataSourceForm" :data-from="'table'" :open-data-source="openDataSource" :event-name="eventName" :data="handlerCache" />
      </template>
    </el-drawer>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { eventSchema } from './fieldWidget'
import CodeEditor from '@/components/desform/online/codeEditor'
import dataSourceForm from '@/components/desform/online/dataSourceForm'
import { saveEventHandler, getEventHandlerByIdAndEventName } from '@/api/system/desform/onlineForm/onlCgformHead'

export default {
  name: 'OnlFormEventDispose',
   components: {
      CodeEditor,
      dataSourceForm
    },
    props: {

    },
   data() {
     return {
          i: 1,
          btnDis: true,
          multipleTable: [],
          tableData: [{}],
          eventSchema: eventSchema.get('table'),
          showWidgetEventDialogFlag: false,
          showDataSourceDialogFlagForm: false,
          eventHandlerCode: undefined,
          eventName: '',
          openDataSource: 'javascript',
          row: {}, // 行数据
          handlerCache: undefined,
          drawerLoading: false
     }
   },
  computed: {
    ...mapState('dbAbout', ['dbPropertyList', 'indexMemory', 'rowData', 'head'])

  },
   watch: {
    rowData: {
      handler() {
          this.tableData[this.rowData.index - 1].fieldShowType = this.rowData.fieldShowType
      },
      deep: true
    },
    // indexMemory: {
    //   handler() {
    //       const { newIndex, oldIndex } = this.indexMemory
    //       const currRow = this.tableData.splice(oldIndex, 1)[0]
    //       this.tableData.splice(newIndex, 0, currRow)
    //       let i = 1
    //       this.tableData.forEach(e => { e.index = i++ })
    //     }
    //  },
    dbPropertyList: {
     handler() {
          this.wrapperData()
    },
    deep: true
    }
  },
   created() {
   },
   methods: {
   // 封装成这个表单需要的数据
     wrapperData() {
       console.log(this.rowData, this.dbPropertyList, this.indexMemory, this.dbPropertyList[0].cgformHeadId, '***********')
      this.tableData = []
       const obj = {
         'index': 1,
         'id': this.head.id
       }
       this.tableData.push(obj)
     },
     openEvent(name) {
        this.showWidgetEventDialogFlag = true
        this.eventName = name
     },
     saveEventHandler() {
        this.showWidgetEventDialogFlag = false
     },
     sourceOpen(name, row) {
       this.initialize()
       this.row = row
       this.drawerLoading = true
        getEventHandlerByIdAndEventName(name, this.head.id).then((res) => {
              if (res.data) {
                this.handlerCache = res.data
                this.openDataSource = res.data.openDataSource === 'N' ? 'javascript' : '数据源'
                this.drawerLoading = false
              }
          this.showDataSourceDialogFlagForm = true
              this.drawerLoading = false
        })
        this.eventName = name
     },
     testDataSource() {

     },
     saveDataSource() {
        // 保存数据源配置
         this.$refs['dataSourceForm'].$refs['form'].validate((valid) => {
              if (valid) {
                // 这里单独进行保存表数据，因为只有编辑的时候才有事件tab所以是能拿到field_id的
                const fieldHandler = this.$refs.dataSourceForm.dsForm
                if (this.handlerCache) {
                    fieldHandler.id = this.handlerCache.id
                }
                fieldHandler.fieldId = this.head.id
                fieldHandler.openDataSource = this.openDataSource === 'javascript' ? 'N' : 'Y'
                // 后台用josn 格式存储把
                fieldHandler.dataSource.rHead = JSON.stringify(fieldHandler.dataSource.rHead)
                fieldHandler.dataSource.rParam = JSON.stringify(fieldHandler.dataSource.rParam)
                  this.drawerLoading = true
                console.log(fieldHandler, 'fieldHandler')
                saveEventHandler(fieldHandler).then(res => {
                   if (res.code === 200) {
                      this.drawerLoading = false
                      this.showDataSourceDialogFlagForm = false
                   }
                })
              }
         })
     },
     // 初始化数据
     initialize() {
       this.i = 1
       this.btnDis = true
         this.multipleTable = []
         this.tableData = [{}]
         this.eventSchema = eventSchema.get('table')
         this.showWidgetEventDialogFlag = false
         this.showDataSourceDialogFlagForm = false
         this.eventHandlerCode = undefined
         this.eventName = ''
         this.openDataSource = 'javascript'
         this.row = {} // 行数据
       this.handlerCache = undefined
         this.drawerLoading = false
     }
  }
}
</script>

<style scoped>
.buttons {
  margin-bottom: 10px;
}
/* 修改行的最小高度 */
.dataForm .el-row .el-form-item {
  min-height: 0px;
}
::v-deep .ds-setting-drawer { /* 必须加上::v-deep，否则不生效 */
    right: 320px !important;
  }

::v-deep .header-small-mb .el-drawer__header {
  margin-bottom: 6px;
}

::v-deep .header-small-mb .el-drawer__body {
  padding: 12px;
}
</style>
